import React from 'react'
import {observer} from 'mobx-react'
import {Button, Divider, NavBar, Popup, Toast} from 'antd-mobile'
import styles from './payment.module.css'
import http from 'libs/http'
import store from './store'

@observer
class Payment extends React.Component {
  state = {
    loading: false,
    showOfflinePopup: false,
    paymentMethod: '',
  }

  // 返回上一页
  handleBack = () => {
    store.currentStep = 'agreement'
  }

  // 生成付款码
  generatePaymentCode = () => {
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const hour = String(now.getHours()).padStart(2, '0')
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
    return `${year}${month}${day}${hour}${random}`
  }

  // 线下汇款
  handleOfflinePayment = () => {
    console.log('用户选择线下汇款')
    this.setState({showOfflinePopup: true})
  }

  // 关闭线下汇款弹窗
  handleCloseOfflinePopup = () => {
    console.log('关闭线下汇款弹窗')
    this.setState({showOfflinePopup: false})
  }

  // 渲染线下汇款信息弹窗
  renderOfflinePopup() {
    // 生成付款码
    const paymentCode = this.generatePaymentCode()
    console.log('生成线下支付付款码:', paymentCode)

    // 获取总金额
    const totalAmount = store.courseTotalPrice || 0

    return (
      <Popup
        visible={this.state.showOfflinePopup}
        onMaskClick={this.handleCloseOfflinePopup}
        bodyStyle={{
          borderTopLeftRadius: '12px',
          borderTopRightRadius: '12px',
          minHeight: '40vh',
          maxHeight: '80vh',
        }}
      >
        <div className={styles.offlinePayment}>
          <div className={styles.popupHeader}>
            <div className={styles.title}>线下汇款信息</div>
            <div className={styles.closeBtn} onClick={this.handleCloseOfflinePopup}>
              关闭
            </div>
          </div>

          <div className={styles.companyInfo}>
            {/* <img src="/logo.png" alt="盟师教育" className={styles.logo} /> */}
            <div className={styles.companyName}>盟师教育</div>
          </div>

          <div className={styles.paymentInfo}>
            <div className={styles.infoCard}>
              <div className={styles.cardTitle}>收款账户信息</div>
              <div className={styles.infoItem}>
                <div className={styles.labelWrapper}>
                  <span className={styles.label}>收款单位：</span>
                </div>
                <div className={styles.value}>上海盟师教育科技有限公司</div>
              </div>

              <div className={styles.infoItem}>
                <div className={styles.labelWrapper}>
                  <span className={styles.label}>银行账号：</span>
                </div>
                <div className={styles.value}>1001734109100103416</div>
              </div>

              <div className={styles.infoItem}>
                <div className={styles.labelWrapper}>
                  <span className={styles.label}>开户银行：</span>
                </div>
                <div className={styles.value}>中国工商银行股份有限公司上海市松江科技城支行</div>
              </div>
            </div>

            <div className={styles.infoCard}>
              <div className={styles.cardTitle}>付款信息</div>
              <div className={styles.infoItem}>
                <div className={styles.labelWrapper}>
                  <span className={styles.label}>付款金额：</span>
                </div>
                <div className={styles.value}>¥ {totalAmount.toFixed(2)}</div>
              </div>

              <div className={styles.infoItem}>
                <div className={styles.labelWrapper}>
                  <span className={styles.label}>付款码：</span>
                </div>
                <div className={styles.value}>{paymentCode}</div>
              </div>
            </div>

            <div className={styles.notice}>
              为准确核实款项，汇款时请务必填写付款码作为备注信息
            </div>

            <Button
              block
              color="primary"
              className={styles.confirmBtn}
              onClick={this.handleOfflineSubmit}
              loading={this.state.loading}
              disabled={this.state.loading}
            >
              确认提交
            </Button>
          </div>
        </div>
      </Popup>
    )
  }

  // 准备订单数据 - 抽取公共方法减少重复代码
  prepareOrderData = (paymentType) => {
    // 检查必要数据
    if (!Array.isArray(store.courseInfo) || store.courseInfo.length === 0) {
      throw new Error('课程信息不完整')
    }

    // 构建学生信息对象
    const studentInfo = {
      name: store.formData.name,
      id_card: store.formData.id_card,
      parent_name: store.formData.parent_name,
      parent_phone: store.formData.parent_phone,
      student_type: store.formData.student_type,
      class_type: store.formData.class_type,
    }

    // 如果是校内上课，添加班级信息
    if (store.formData.class_type === 'in_school') {
      studentInfo.grade = store.formData.grade

      // 处理 class_number 可能是数组的情况
      if (Array.isArray(store.formData.class_number) && store.formData.class_number.length > 0) {
        studentInfo.class_number = store.formData.class_number[0]
      } else {
        studentInfo.class_number = store.formData.class_number
      }
    }

    // 确保 courseInfo 是数组
    const courses = Array.isArray(store.courseInfo) ? store.courseInfo : []

    // 构建完整的订单数据
    const orderData = {
      payment_type: paymentType,
      student_info: studentInfo,
      school_info: {
        name: store.schoolName,
        exam_year: store.examYear,
      },
      course_ids: courses.map(course => course.id),
      total_amount: store.courseTotalPrice || 0,
    }

    // 根据支付类型添加特定字段
    if (paymentType === 'offline') {
      orderData.payment_code = this.generatePaymentCode()
    } else if (paymentType === 'wechat') {
      // 确保有 openid
      if (!store.openid) {
        throw new Error('未获取到用户信息，请重新授权')
      }
      orderData.openid = store.openid
    }

    console.log('准备提交的订单数据:', orderData)
    return orderData
  }

  // 创建订单 - 通用方法
  createOrder = async (paymentType) => {
    try {
      const orderData = this.prepareOrderData(paymentType)
      console.log('开始创建订单，支付方式:', paymentType)

      // 显示加载提示
      Toast.show({
        icon: 'loading',
        content: '正在创建订单...',
        position: 'center',
        duration: 0
      })

      const res = await http.post('/api/app/order/', orderData)

      // 关闭加载提示
      Toast.clear()

      console.log('订单创建响应:', res)

      if (!res || !res.order_id) {
        throw new Error('创建订单失败: 服务器返回数据不完整')
      }

      return res
    } catch (error) {
      // 关闭加载提示
      Toast.clear()

      console.error('创建订单失败:', error)
      Toast.show({
        icon: 'fail',
        content: error.message || '创建订单失败',
        position: 'top'
      })
      throw error
    }
  }

  // 处理微信支付
  handleWechatPayment = async () => {
    // const isWxClient = /MicroMessenger/i.test(navigator.userAgent)
    // if (!isWxClient) {
    //   Toast.show({content: '请在微信中打开'})
    //   return
    // }
    // this.setState({loading: true, paymentMethod: 'wechat'})
    // 检查是否有openid
    // 创建订单
    const orderRes = await this.createOrder('wechat')

    if (!orderRes || !orderRes.order_id) {
      throw new Error('创建订单失败')
    }

    // 调用微信支付
    if (typeof window.WeixinJSBridge !== 'undefined') {
      console.log('检测到 WeixinJSBridge，调用支付接口')

      store.orderid = orderRes.order_id
      window.WeixinJSBridge.invoke('getBrandWCPayRequest', orderRes.pay_params, (result) => {
        console.log('微信支付结果:', result)

        if (result.err_msg === 'get_brand_wcpay_request:ok') {
          console.log('支付成功，准备跳转到成功页面')
          store.currentStep = 'success'
        } else if (result.err_msg === 'get_brand_wcpay_request:cancel') {
          console.log('用户取消支付')
          Toast.show({
            icon: 'fail',
            content: '支付已取消',
            position: 'top'
          })
        } else {
          console.error('支付失败:', result.err_msg)
          Toast.show({
            icon: 'fail',
            content: '支付失败: ' + result.err_msg,
            position: 'top'
          })
        }
        this.setState({loading: false, paymentMethod: ''})
      })
    }
  }

  // 处理线下支付
  handleOfflineSubmit = async () => {
    console.log('用户确认线下汇款')
    this.setState({loading: true, paymentMethod: 'offline'})

    try {
      console.log('开始创建线下支付订单')
      const orderRes = await this.createOrder('offline')

      if (!orderRes || !orderRes.order_id) {
        throw new Error('创建订单失败: 服务器返回数据不完整')
      }

      Toast.show({
        icon: 'success',
        content: '订单创建成功',
        position: 'top'
      })

    } catch (error) {
      console.error('创建线下支付订单失败:', error)
      Toast.show({
        icon: 'fail',
        content: error.message || '创建订单失败',
        position: 'top'
      })
    } finally {
      this.setState({loading: false, showOfflinePopup: false, paymentMethod: ''})
    }
  }

  render() {
    const {loading} = this.state

    // 从 store 中获取数据，并提供默认值
    const courseTotalPrice = store.courseTotalPrice || 0
    const paidAmount = store.paidAmount || 0
    const agreementNo = store.agreementNo || ''
    const schoolName = store.schoolName || ''
    const examYear = store.examYear || ''

    console.log('store.formData in payment', store.formData)
    // 确保 formData 是对象
    const formData = typeof store.formData === 'object' && store.formData !== null
      ? store.formData
      : {}

    // 确保 courseInfo 是数组
    let courses = []
    try {
      courses = Array.isArray(store.courseInfo) ? [...store.courseInfo] : []
    } catch (error) {
      console.error('Error accessing courseInfo:', error)
      courses = []
    }

    return (
      <div className={styles.container}>
        <NavBar onBack={this.handleBack} className={styles.navBar}>我的学费</NavBar>

        {/* 基本信息 */}
        <div className={styles.basicInfo}>
          <div className={styles.infoItem}>
            <span>协议号：</span>
            <span>{agreementNo}</span>
          </div>
          <div className={styles.infoItem}>
            <span>学员姓名：</span>
            <span>{formData.name}</span>
          </div>
          <div className={styles.infoItem}>
            <span>学校：</span>
            <span>{schoolName}</span>
          </div>
          <div className={styles.infoItem}>
            <span>应届高考年份：</span>
            <span>{examYear}</span>
          </div>
          <div className={styles.infoItem}>
            <span>上课类型：</span>
            <span>{formData.class_type === 'in_school' ? '校内上课' : '校外上课'}</span>
          </div>
          {formData.class_type === 'in_school' && (
            <div className={styles.infoItem}>
              <span>班级信息：</span>
              <span>
                {formData.grade === 'grade_1' ? '高一' :
                  formData.grade === 'grade_2' ? '高二' : '高三'}
                {Array.isArray(formData.class_number) && formData.class_number.length > 0
                  ? formData.class_number[0].replace('class_', '') + '班'
                  : formData.class_number && typeof formData.class_number === 'string'
                    ? formData.class_number.replace('class_', '') + '班'
                    : ''}
              </span>
            </div>
          )}
        </div>

        {/* 总金额信息 */}
        <div className={styles.amountInfo}>
          <div className={styles.amountItem}>
            <span>¥{courseTotalPrice.toFixed(2)}</span>
            <span>总金额</span>
          </div>
          <div className={styles.amountItem}>
            <span>¥{paidAmount}</span>
            <span>已缴金额</span>
          </div>
          <div className={styles.amountItem}>
            <span>¥{(courseTotalPrice - paidAmount).toFixed(2)}</span>
            <span>待缴金额</span>
          </div>
        </div>

        {/* 缴费项目列表 */}
        <div className={styles.itemList}>
          {courses.map(item => (
            <div key={item.id || Math.random()} className={styles.paymentItem}>
              <div className={styles.itemHeader}>
                <span>{item.name || '未命名课程'}</span>
                <span className={styles.deadline}>
                  截止日期：{item.start_date || '待定'}
                </span>
              </div>
              <div className={styles.itemContent}>
                <div>
                  <div>订单金额：¥ {item.price || 0}</div>
                </div>
                <div className={styles.remainAmount}>
                  待缴金额：¥ {item.price || 0}
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* 支付按钮 */}
        <div className={styles.footer}>
          <div className={styles.totalAmount}>
            本次应缴金额：¥{courseTotalPrice.toFixed(2)}
          </div>
          <Divider/>
          <div className={styles.payButtons}>
            <Button
              className={styles.offlineBtn}
              onClick={this.handleOfflinePayment}
              loading={loading && this.state.paymentMethod === 'offline'}
              disabled={loading}
            >
              线下汇款
            </Button>
            <Button
              className={styles.wechatBtn}
              loading={loading && this.state.paymentMethod === 'wechat'}
              onClick={this.handleWechatPayment}
              disabled={loading}
            >
              微信支付
            </Button>
          </div>
        </div>

        {/* 渲染线下汇款弹窗 */}
        {this.renderOfflinePopup()}
      </div>
    )
  }
}

export default Payment